const AllGroup = require('../models/allGroupModel');
const User = require('../models/userModel');

const sendMessage = (req, res) => {
  const { senderId, message } = req.body;

  // 更新发送者的最后活跃时间
  User.updateLastActive(senderId, (err) => {
    if (err) {
      console.error('Error updating last active:', err);
    } else {
      console.log(`User ${senderId} last active time updated`);
    }
  });

  AllGroup.sendMessage(senderId, message, (err, messageId) => {
    if (err) {
      console.error('Error saving message:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    res.json({ messageId, message: 'Message sent to all group successfully' });
  });
};

const getMessages = (req, res) => {
  AllGroup.getMessages((err, messages) => {
    if (err) {
      console.error('Error fetching messages:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    res.json(messages);
  });
};

const getRecentMessages = (req, res) => {
  const { limit = 10 } = req.query; // 默认返回最近 10 条消息

  AllGroup.getRecentMessages(limit, (err, messages) => {
    if (err) {
      console.error('Error fetching recent messages:', err);
      return res.status(500).json({ error: 'Database error' });
    }
    res.json(messages);
  });
};

module.exports = { sendMessage, getMessages, getRecentMessages }; 